package com.project.controller;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.project.bean.SupplierBean;
import com.project.service.ISupplierService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("supplier")
@Api(tags = "供应商控制层")
public class SupplierController {
    @Autowired
    private ISupplierService supplierService;

    @ApiOperation("分页动态查询供应商信息")
    @GetMapping("cutByItem")
    public IPage<SupplierBean> cutByItem(Integer pageNO, String name, String scope){
        return supplierService.cutByItem(pageNO,name,scope);
    }

    @ApiOperation("按id查询供应商信息")
    @GetMapping("findById")
    public SupplierBean findById(Integer supplierId){
        return supplierService.findById(supplierId);
    }

    @ApiOperation("通过id修改负责人电话")
    @PutMapping("update")
    public String update(Integer supplierId, String newHead, String newPhone){
        supplierService.update(supplierId,newHead,newPhone);
        return "ok";
    }


    @GetMapping("findSupplier")
    @ApiOperation("通过名字查看供应商是否存在")
    public String findSupplier(String name){
        SupplierBean supplier = supplierService.findSupplier(name);
        if(supplier==null){
            return "no";
        }else {
            return "ok";
        }
    }

    @ApiOperation("添加")
    @PostMapping("add")
    public String add(@RequestBody SupplierBean supplier){
        supplierService.add(supplier);
        return "ok";
    }

    @ApiOperation("查询所有")
    @GetMapping("findSupplierList")
    public List<SupplierBean> findSupplierList(){
        return supplierService.findSupplierList();
    }

    @ApiOperation("上传Excel")
    @PostMapping("uploadExcel")
    public String upload(MultipartFile excelFile) throws Exception{
        ImportParams params = new ImportParams();        //创建对象
        params.setSheetNum(1);//第几页的表
        params.setTitleRows(1);//标题占几行
        params.setHeadRows(1);//表头占几行

        List<SupplierBean> supplierList = ExcelImportUtil.importExcel(excelFile.getInputStream(), SupplierBean.class, params);
        supplierList.forEach(supplier -> {
            if(supplierService.findSupplier(supplier.getName())==null){
                supplierService.add(supplier);
            }
        });
        return "ok";
    }

}
